#!/bin/bash
while getopts d:ae: flag
do
  case "${flag}" in
    d) dirname=${OPTARG};;
    e) ext=${OPTARG};;
    *) echo "Incorrect options passed " && exit 1
  esac
done
length=${#dirname}
last_char=${dirname:length-1:1}
[[ $last_char != "/" ]] && dirname="$dirname/" 
echo -n "Check -d option ... "
if [[ -z $dirname ]]; then
    echo " Fail"
    exit 1
fi
echo " OK"
echo -n "Check target folder ..."
if [[ ! -d $dirname ]]; then
    echo " Fail"
    exit 1
fi
echo " OK"
echo -n Check default editor ...
if [[ -z $EDITOR ]]; then
    echo " Default editor is not set"
    exit 1
fi
echo " OK"
echo -n "get latest report in $dirname ... "
if [[ ! -z $ext ]]; then
  filename_mask="$dirname""*.$ext"
else 
  filename_mask="$dirname""*.*"
fi
last_report=$(ls -1t $filename_mask | head -n 1)
if [[ -z $last_report ]]; then
   echo "Hmm ... Fail.Nothing for view"
   exit 1 
fi
echo " OK"
echo $last_report
read
nvim -R $last_report

